// src/stores/user.js
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  const username = ref('')
  const password = ref('')
  const rememberMe = ref(false)

  function setUser(newUsername, newPassword, remember) {
    username.value = newUsername
    password.value = newPassword
    rememberMe.value = remember
    if (remember) {
      localStorage.setItem('rememberedUser', JSON.stringify({
        username: newUsername,
        password: newPassword
      }))
    } else {
      localStorage.removeItem('rememberedUser')
    }
  }

  function loadRememberedUser() {
    const rememberedUser = JSON.parse(localStorage.getItem('rememberedUser'))
    if (rememberedUser) {
      username.value = rememberedUser.username
      password.value = rememberedUser.password
      rememberMe.value = true
    }
  }

  function clearUser() {
    username.value = ''
    password.value = ''
    rememberMe.value = false
    localStorage.removeItem('rememberedUser')
  }

  return { username, password, rememberMe, setUser, loadRememberedUser, clearUser }
})